package com.wisdytech.ccdserver.common.utils;

import com.wisdytech.ccdserver.common.config.MinioConfig;
import com.wisdytech.ccdserver.common.dto.FileDto;
import com.wisdytech.common.utils.SnowFlake;
import io.minio.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * minio帮助类
 *
 * @author svolt
 */
public class MinioUtils {


    public static void doBucketName(String bucketName, MinioClient client) throws IOException {
        BucketExistsArgs bucket = BucketExistsArgs.builder().bucket(bucketName).build();
        boolean exist = false;
        try {
            exist = client.bucketExists(bucket);
            if (!exist) {
                client.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            }
        } catch (Exception e) {
            throw new IOException(e.getMessage(), e);
        }
    }

    public static FileDto uploadFile(MultipartFile file, SnowFlake snowFlake, MinioConfig minioConfig, MinioClient client) throws Exception {
        String fileName = "";
        fileName = "trace/" + DateUtils.datePath() + "/" + DateUtils.dateTimeMis() + "_" + snowFlake.nextStringId() + "_" + file.getOriginalFilename();
        //存储桶不存在创建，存在不创建
        MinioUtils.doBucketName(minioConfig.getBucketName(), client);
        PutObjectArgs args = PutObjectArgs.builder()
                .bucket(minioConfig.getBucketName())
                .object(fileName)
                .stream(file.getInputStream(), file.getSize(), -1)
                .contentType(file.getContentType())
                .build();
        client.putObject(args);
        FileDto fileDto = new FileDto();
        fileDto.setName(file.getOriginalFilename());
        fileDto.setUrl(minioConfig.getOuterUrl() + "/" + minioConfig.getBucketName() + "/" + fileName);
        return fileDto;
    }

    /**
     * 宝马专用文件上传
     *
     * @param file
     * @param snowFlake
     * @param minioConfig
     * @param client
     * @return
     * @throws Exception
     */
    public static FileDto uploadFileBMW(MultipartFile file, SnowFlake snowFlake, MinioConfig minioConfig, MinioClient client) throws Exception {
        String fileName = "";
        fileName = "trace/" + DateUtils.datePath() + "/" + DateUtils.dateTimeMis() + "_" + snowFlake.nextStringId() + "_" + "fengxianjizu.xlsx";
        //存储桶不存在创建，存在不创建
        MinioUtils.doBucketName(minioConfig.getBucketName(), client);
        PutObjectArgs args = PutObjectArgs.builder()
                .bucket(minioConfig.getBucketName())
                .object(fileName)
                .stream(file.getInputStream(), file.getSize(), -1)
                .contentType(file.getContentType())
                .build();
        client.putObject(args);
        FileDto fileDto = new FileDto();
        fileDto.setName(file.getOriginalFilename());
        fileDto.setUrl(minioConfig.getOuterUrl() + "/" + minioConfig.getBucketName() + "/" + fileName);
        return fileDto;
    }

    public static void fileDownload(String fileName, HttpServletResponse response, MinioClient client, MinioConfig minioConfig) {

        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            if (StringUtils.isBlank(fileName)) {
                response.setHeader("Content-type", "text/html;charset=UTF-8");
                String data = "文件下载失败";
                OutputStream ps = response.getOutputStream();
                ps.write(data.getBytes("UTF-8"));
                return;
            }

            outputStream = response.getOutputStream();
            // 获取文件对象
            inputStream = client.getObject(GetObjectArgs.builder().bucket(minioConfig.getBucketName()).object(fileName).build());
            byte buf[] = new byte[1024];
            int length = 0;
            response.reset();
            response.setHeader("Content-Disposition", "attachment;filename=" +
                    URLEncoder.encode(fileName.substring(fileName.lastIndexOf("/") + 1), "UTF-8"));
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("UTF-8");
            // 输出文件
            while ((length = inputStream.read(buf)) > 0) {
                outputStream.write(buf, 0, length);
            }
            inputStream.close();
            // 判断：下载后是否同时删除minio上的存储文件
//            if (BooleanUtils.isTrue(delete)) {
//                client.removeObject(RemoveObjectArgs.builder().bucket(minioConfig.getBucketName()).object(fileName).build());
//            }
        } catch (Throwable ex) {
            response.setHeader("Content-type", "text/html;charset=UTF-8");
            String data = "文件下载失败";
            try {
                OutputStream ps = response.getOutputStream();
                ps.write(data.getBytes("UTF-8"));
            } catch (IOException e) {
                e.printStackTrace();
            }
        } finally {
            try {
                outputStream.close();
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
